<template>
    <div class="box-card">
      <div class='monitor'>
        <div class="title">
          <p class="title-name">运行监测</p>
        </div>

        <el-form
          :model="form"
          ref="queryForm"
          :inline="true"
          label-width="68px"
        >
          <el-form-item prop="equipId" :inline="true" class='el-width-110'>
            <el-select
              placeholder="请选择设备"
              v-model="form.equipId"
              size="mini"
              @change="selectEquip"
            >
              <el-option
                v-for="item in equipList"
                :key="item.equipId"
                :label="item.equipName"
                :value="item.equipId"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <template v-if="indexList && indexList.length">
            <el-form-item class="btn-wrap">
              <el-button
                v-for='item in indexList' :key="item.indexConfigCode"
                :type="activeName == item.indexConfigCode ? 'primary' : ''"
                size="mini"
                @click="changeBtn(item)"
              >{{item.indexConfigName}}
                <span v-if='item.indexValue != null && item.indexValue != undefined && String(item.indexValue) != ""'>
                  <span>：{{item.ifEquipRunStatusIndex === true ? getEquipStatusLabel(item.indexValue) : toFix(item.indexValue, 2)}}</span>
                  <span v-if='item.indexValueUnit && item.indexValueUnit != "无"'>{{item.indexValueUnit}}</span>
                </span>
              </el-button>
            </el-form-item>
            <div class="more" @click="showToggle" v-text='isShort ? "更多" : "收起"'  v-if='indexList && indexList.length'></div>
          </template>

          <div class="error-tip" v-else>
            暂无数据
          </div>
        </el-form>
      </div>

      <!-- 折线图 -->
      <div v-show='isShowDiv' v-loading="loading">
        <div class="chart-wrap" v-show="(chartDataX && chartDataX.length && chartDataY && chartDataY.length)">
          <div
            ref="monitorChart"
            class="chart-content"
            style="{width: 100%;height: 500px;}"
          >
          </div>
        </div>
        <div class="error-tip" v-show="(!(chartDataX && chartDataX.length && chartDataY && chartDataY.length)) && indexList && indexList.length">
          近2小时内暂无数据
        </div>
      </div>
    </div>
</template>
<script>
  import {getEquipByLineIds,getEquipIndexByEquipId,getIndexValueDatas} from "@/api/workbench/index";
  import { getMaterialConsumeOption,getMonitorOption, getEquipStatusOption } from '../echartOption'
  import { mapState,mapActions,mapGetters} from "vuex";
  import { getEquipStatusLabel } from "../equipStatus";
export default {
  props:{
    queryData:{
      type:String,
      default:""
    },
    queryType:{
      type:String,
      default:""
    },
    lineIds:{
      type:String,
      default:""
    }
  },

  data() {
    return {
      activeName:"",
      form:{
        equipId:""
      },
      isShort:true,
      queryParams:"",
      equipList:[],
      loading: false,
      isShowDiv:false,
      indexList:[],
      echartsInstance: null,
      indexValueUnit: "",
      chartDataX:[],
      chartDataY:[],
      abnormalMin:[],
      abnormalMax:[],
      warnMin:[],
      warnMax:[],
      refreshTimer:null,
      getEquipStatusLabel,
    };
  },

  methods:{
    setRefreshTimer(){
      if (this.refreshTimer) {
        clearTimeout(this.refreshTimer);
        if(this.echartsInstance){
          this.echartsInstance.off("click");
        }
      }
      this.refreshTimer = setTimeout(() => {
        this.geEquipmentList()
        this.setRefreshTimer();
      },60000)
    },

    //获取设备列表
    geEquipmentList(){
      this.loading = true;
      let query = {}
      if(this.queryType == "line"){
        query.lineIds = this.queryParams;
      }
      else if(this.queryType == "station"){
        query.workStationId = this.queryParams;
      }
      getEquipByLineIds(query)
      .then((res) => {
        if(res.code == 200 && res?.data?.length){
          this.equipList = res?.data || [];
          if(this.equipList?.length){
            this.form.equipId = this.form.equipId ? this.form.equipId : this.equipList[0]?.equipId;
            this.getEquipIndexByEquipIdList()
          }
        }
        else{
          this.equipList = [];
          this.form.equipId = "";
          this.indexAllList = [];
          this.indexShort = [];
          this.indexList = [];
          this.activeName = "";
          this.indexValueUnit = "";
        }
        this.loading = false;
      })
      .catch(() => {
        this.equipList = [];
        this.loading = false;
      });
    },

    //根据设备获取指标
    getEquipIndexByEquipIdList(){
      if(!this.form?.equipId){
        return
      }
      this.loading = true;
      getEquipIndexByEquipId(this.form)
      .then((res) => {
        if(res.code == 200 && res?.data?.length){
          this.indexAllList = [...res?.data ]|| [];
          this.indexShort = [...res?.data].slice(0,6);
          this.indexList = this.isShort ? [...this.indexShort] : [...this.indexAllList];
          this.activeName = this.activeName ? this.activeName : this.indexList[0]?.indexConfigCode || "";
          this.indexValueUnit = this.indexValueUnit ? this.indexValueUnit : this.indexList[0]?.indexValueUnit || "";
          this.getIndexValueDatas()
        }else{
          this.indexAllList = [];
          this.indexShort = [];
          this.indexList = [];
          this.activeName = "";
          this.indexValueUnit = "";
          this.chartDataX = [];
          this.chartDataY = [];
          this.isShowDiv = false;
        }
        this.loading = false;
      })
      .catch(() => {
        this.indexAllList = [];
        this.indexShort = [];
        this.indexList = [];
        this.activeName = "";
        this.indexValueUnit = "";
        this.loading = false;
      });
    },

    //获取指标趋势
    getIndexValueDatas(){
      this.loading = true;
      const parmas = {
        lineIds:this.lineIds,
        indexConfigCode:this.activeName,
        dayRange:2
      }
      getIndexValueDatas(parmas)
      .then((res) => {
        if(res.data?.indexValueVos?.length){
          const list = res.data?.indexValueVos || [];
          const warnRules = res.data?.warnRules || [];
          const abnormalRules = res.data?.abnormalRules || [];
          let warnMaxList = [];
          let warnMinList = [];
          let abnormalMaxList = [];
          let abnormalMinList = [];
          this.warnMin = [];
          this.warnMax = [];
          this.abnormalMin = [];
          this.abnormalMax = [];
          if(list?.length){
            this.chartDataX = list.map(ele => ele.dateStr);
            this.chartDataY = list.map(ele => ele.indexValue);
          }
          if(warnRules?.length){
            this.warnMin = warnRules.map((item,index) => {
              warnMinList[index] = [];
              for(let i = 0; i<list.length; i++){
                if(item.warnMin != undefined && item.warnMin != null && String(item.warnMin) != ""){
                  warnMinList[index].push(item.warnMin)
                }
              }
              return warnMinList[index]
            })
            this.warnMax = warnRules.map((item,index) => {
              warnMaxList[index] = [];
              for(let i = 0; i<list.length; i++){
                if(item.warnMax != undefined && item.warnMax != null && String(item.warnMax) != ""){
                  warnMaxList[index].push(item.warnMax)
                }
              }
              return warnMaxList[index]
            })
          }

          if(abnormalRules?.length){
            this.abnormalMin = abnormalRules.map((item,index) => {
              abnormalMinList[index] = [];
              for(let i = 0; i<list.length; i++){
                if(item.abnormalMin != undefined && item.abnormalMin != null && String(item.abnormalMin) != ""){
                  abnormalMinList[index].push(item.abnormalMin)
                }
              }
              return abnormalMinList[index]
            })

            this.abnormalMax = abnormalRules.map((item,index) => {
              abnormalMaxList[index] = [];
              for(let i = 0; i<list.length; i++){
                if(item.abnormalMax != undefined && item.abnormalMax != null && String(item.abnormalMax) != ""){
                  abnormalMaxList[index].push(item.abnormalMax)
                }
              }
              return abnormalMaxList[index]
            })
          }
          if (this.chartDataX?.length && this.chartDataY?.length ){
            this.$nextTick(()=>{
              this.initChart()
            })
          }
        }
        else{
          this.indexValueUnit = "";
          this.chartDataX = [];
          this.chartDataY = [];
          this.isShowDiv = true;
        }
        this.loading = false;
        this.isShowDiv = true;
      })
      .catch(() => {
        this.indexValueUnit = "";
        this.chartDataX = [];
        this.chartDataY = [];
        this.isShowDiv = true;
        this.loading = false;
      });
    },

    changeBtn(item){
      this.activeName = item.indexConfigCode;
      this.indexValueUnit = item.indexValueUnit;
      this.getIndexValueDatas()
    },

    initChart(){
      // 基于准备好的dom，初始化echarts实例
      this.echartsInstance = null;
      this.echartsInstance = this.$echarts.init(this.$refs.monitorChart, null, {renderer:'svg'})

      let option = {}

      const indexItem = this.indexList.find(ele => ele.indexConfigCode === this.activeName);
      if (indexItem?.ifEquipRunStatusIndex === true) {
        option = getEquipStatusOption(this.chartDataX, this.chartDataY)
      } else {
        // 指定图表的配置项和数据
        option = getMonitorOption(this.chartDataX,this.chartDataY,this.warnMin,this.warnMax,this.abnormalMin,this.abnormalMax, this.indexValueUnit)
      }
      // 使用刚指定的配置项和数据显示图表。
      this.echartsInstance.setOption(option,true)
    },

    resize() {
      this.echartsInstance?.resize()
    },

    selectEquip(){
      this.activeName = "";
      this.indexValueUnit = "";
      this.getEquipIndexByEquipIdList()
    },

    showToggle(){
      this.isShort = !this.isShort
      if(this.isShort){
        this.indexList = [...this.indexShort];
      }else{
        this.indexList = [...this.indexAllList];
      }
    }
  },

  watch:{
    queryData:{
      handler(newVal){
        if(newVal){
          this.queryParams = newVal;
        }
        this.geEquipmentList()
        // 清除轮询
        if (this.refreshTimer) {
          clearTimeout(this.refreshTimer);
          if(this.echartsInstance){
            this.echartsInstance.off("click");
          }
        }
        this.setRefreshTimer()
      },
      deep: true,
      immediate: true
    }
  },
  beforeDestroy(){
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
      if(this.echartsInstance){
        this.echartsInstance.off("click");
      }
    }
  },
  destroyed(){
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
      if(this.echartsInstance){
        this.echartsInstance.off("click");
      }
    }
  }
};
</script>
<style lang="scss" scoped>
  .monitor{
    .title{
      display:flex;
      align-items: center;
      font-size: 14px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #1F2E4D;
      .title-name{
        margin-right:16px;
      }
    }
    ::v-deep .el-form{
      display: flex;
      flex-wrap: wrap;
      .btn-wrap{
        flex:1;
        .el-form-item__content{
          width:100%;
          button{
            // width: 16%;
            margin-right: 6px;
            margin-left: 0;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
      .more{
        cursor: pointer;
        width: 62px;
        height: 28px;
        margin-top:2px;
        border-radius: 2px;
        border: 1px solid #34855C;
        text-align: center;
        line-height:28px;
        background-color: #fff;
        color:#34855B
      }
    }
  }
  .chart-wrap{
    width: 100%;
    height: 560px;
    display:flex;
    align-items: center;
    justify-content: center;
    .chart-content{
      width: 100%;
      height: 100%;
      color: #909399;
    }
  }
  .error-tip{
    width: 100%;
    font-size:14px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    color:#909399;
  }
</style>
